<script setup >
import { defineAsyncComponent, ref, provide, watchEffect, onMounted } from 'vue';
import FilterableTable from '../../components/FilterableTable.vue';
import SearchBar from '/src/components/SearchBar.vue'
import Pagination from '/src/components/Pagination_lxw.vue'
import getRequest from '../../utils/lxw_request';
import MyModal from '../../components/MyModal.vue'


const data_name = ref('registered');

const query = ref('')

const grid_columns = new Map();
grid_columns.set('registered', 
[
    {key: 'name', label: '名字', isEnumerable: false},
    {key: 'nickName', label: '昵称', isEnumerable: false},
    {key: 'number', label: '工号', isEnumerable: false},
    {key: 'phone', label: '手机号', isEnumerable: false},
    {key: 'email', label: '邮箱', isEnumerable: false},
    {key: 'school', label: '学校', isEnumerable: false}
]);

const enum_map = new Map();
enum_map.set(0, "未注册");
enum_map.set(1, "已注册");
grid_columns.set('total',
[
    {key: 'name', label: '名字', isEnumerable: false},
    {key: 'number', label: '工号', isEnumerable: false},
    {key: 'school', label: '学校', isEnumerable: false},
    {key: 'isRegistered', label: '是否注册', isEnumerable: true, enum: enum_map}
]);



const grid_data = ref(null)


//API
const total = ref(0);
const current = ref(1)
const pageSize = ref(10)
const role = ref(1)

function changeCurrentPage(cur) {
    current.value = cur;
}

function changePageSize(size) {
    pageSize.value = size;
}

function getSchoolAdministrators() {
    if(data_name.value === 'registered') {
        const search_params = new URLSearchParams();
        search_params.set("current", current.value);
        search_params.set("pageSize", pageSize.value);
        search_params.set("role", role.value);
        if(query.value !== "") {
            search_params.set("like", query.value)
        }
        getRequest(`/admin/users?${search_params.toString()}`, "GET", new Headers({ 'Content-Type': 'application/json' }))
            .then((response) => response.json())
            .then((json) => {
                if (json.code === 200) {
                    grid_data.value = json.data.records === undefined ? null : json.data.records;
                    total.value = json.data.total;
                } else {
                    alert(json.msg);
                }
            })
            .catch((err) => {
                console.error(err);
            })

    } else if(data_name.value === 'total') {
        const search_params = new URLSearchParams();
        search_params.set("current", current.value);
        search_params.set("pageSize", pageSize.value);
        getRequest(`/admin/subAdmin?${search_params.toString()}`, "GET", new Headers({ 'Content-Type': 'application/json' }))
            .then((response) => response.json())
            .then((json) => {
                if (json.code === 200) {
                    grid_data.value = json.data.records === undefined ? null : json.data.records;
                    total.value = json.data.total;
                } else {
                    alert(json.msg);
                }
            })
            .catch((err) => {
                console.error(err);
            })
    }

}

function downloadExcel() {
    const search_params = new URLSearchParams();
    search_params.set("role", role.value);
    getRequest(`/admin/users/excel?${search_params.toString()}`, "GET")
        .then(res => res.blob())
        .then(blob => {
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = "userList.xlsx";
            a.click();
            URL.revokeObjectURL(url);

        })
        .catch((err) => {
            console.error(err);
        })
}


watchEffect(() => {
    getSchoolAdministrators();
})

provide("getUsers", getSchoolAdministrators);

function changeData(name) {
    data_name.value = name;
}


const import_file_ref = ref(null)

function importExcel() {
    const formData = new FormData();

    

    for(const file of this.import_file.value) {
        formData.append("file", file);
    }

    getRequest(`/admin/subAdmin/excel`, "POST", new Headers(), formData)
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                alert("导入学校管理员名单成功")
                getSchoolAdministrators();
                closeModal();
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })
    
}

function openFileExplorer() {
    import_file_ref.value.click();
}

onMounted(() => {
    import_file_ref.value.addEventListener("input", () => {
        importExcel();
    })
})

function deleteUserInfo({subId}) {
    getRequest(`/admin/subUser/${subId}`, "DELETE", new Headers({ 'Content-Type': 'application/json' }))
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                alert("删除成功")
                getSchoolAdministrators();
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })
}


// modal
const isOpenModal = ref(false);
const modal_name = ref('');
const BatchImportForm = defineAsyncComponent(() => import('../../components/BatchImportForm.vue'))
const OnePieceImportForm = defineAsyncComponent(() => import('../../components/OnePieceImportForm.vue'));

function openModal(name) {
    isOpenModal.value = true;
    modal_name.value = name;
}
function closeModal() {
    isOpenModal.value = false;
    modal_name.value = '';
}


const info_key_map = [
    {key: 'name', label: '姓名', isEdit: true, isEnum: false},
    {key: 'school', label: '学校', isEdit: true, isEnum: false},
    {key: 'college', label: '学院', isEdit: true, isEnum: false},
    {key: 'major', label: '专业', isEdit: true, isEnum: false},
    {key: 'grades', label: '班级', isEdit: true, isEnum: false},
    {key: 'number', label: '工号', isEdit: true, isEnum: false}

]

function onePieceImport({type}) {
    const body = {}
    for(const property in this.edit_info) {
        body[property] = this.edit_info[property].value;
    }
    body['type'] = type;
    getRequest(`/admin/subUser`, "POST", new Headers(), JSON.stringify(body))
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                alert("导入学生名单成功")
                getSchoolAdministrators();
                closeModal();
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })
}

</script>
<template>
    <div class="management" >
        <div class="content" >
            <div class="header" >
                <div  v-if="data_name === 'total'" >
                    <div class="btn"  @click="openModal('batch_import')">批量导入</div>
                    <div class="btn" @click="openModal('one_piece_import')" >单条导入</div>
                </div>
                <div v-if="data_name === 'registered'" >  
                    
                    <div class="btn" @click="downloadExcel"  >导出</div>
                    
                </div>
                <input type="file" style="display: none;"  accept=".xlsx"  ref="import_file_ref" />
                <SearchBar :placeholder="'请输入'"  v-model:query="query" class="search-bar" />

            </div>
            <div class="main" >
                <div class="in-and-out" >
                    <div class="button" :class="{active: data_name === 'registered', inactive: data_name !== 'registered'}" @click="changeData('registered')" >已注册</div> 
                    <div class="button" :class="{active: data_name === 'total', inactive: data_name !== 'total'}" @click="changeData('total')" >全部</div> 
                </div>
                <div style="width: 100%; height: 615px;" >
                    <FilterableTable :data="grid_data" :columns="grid_columns.get(data_name)" :style="{width: '100%'}" v-bind:editable="data_name === 'registered'" 
                    v-bind:deletable="data_name === 'total'"  v-bind:delete-function="deleteUserInfo"  v-bind:delete-params="['subId']" />
                </div>
            </div>
            <div class="footer" >
                <Pagination :total="total" @change-current-page="changeCurrentPage" @change-per-page-size="changePageSize" />
            </div>
        </div>
        <MyModal v-model:is-open-modal="isOpenModal" >
            <BatchImportForm  v-if="modal_name === 'batch_import'" :cancel-function="closeModal" :confirm-function="importExcel" />
            <OnePieceImportForm  v-if="modal_name === 'one_piece_import'" :cancel-function="closeModal" :title="'单条导入学校管理员'" :map="info_key_map" :confirm-function="onePieceImport" :confirm-params="{type: 1}" />
        </MyModal>
    </div>

</template>
<style scoped >

.management {
    width: 100%;

}

.content {
    margin: 20px auto;
}

.management {
    width: 100%;
}

.content {
    margin: 20px auto;width: 100%;
}

.header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    height: 45px;
}

.search-bar {
    width: 400px;
    height: 100%;
}

.main {
    margin-bottom: 20px;
}

.in-and-out {
    width: 19.5%;
    display: flex;
    justify-content:space-between;
}

.btn {
    display: inline-block;
    width: 120px;
    border-radius: 5px;
    color: #ffffff;
    letter-spacing: 1px;
    text-align: center;
    cursor: pointer;
    user-select: none;
    opacity: 1;
    margin-right: 15px;
    font-size: 20px;
    height: 35px;
    line-height: 35px;
	background-color: #8493a6;
	box-shadow: 0px 3px 6px 0px 
		rgba(0, 0, 0, 0.16);
	border-radius: 6px;

}


.button.inactive {
    background-color: #606266;
}

.button.active {
    background-color: #8394a6;
}

.search-bar {
    width: 350px;
}

.main {
    margin-bottom: 20px;
}

.in-and-out {
    margin-bottom: 15px;
}

.button {
    display: inline-block;
    width: 45%;
    height: 100%;
    border-radius: 5px;
    color: #ffffff;
    line-height: 35px;
    letter-spacing: 1px;
    text-align: center;
    cursor: pointer;
    user-select: none;
    opacity: 1;
    font-size: 14px;
    margin-right: 15px;
    font-size: 20px;
}

.button:hover {
    opacity: 0.8;
}

.button:active {
    transform: translateY(3px);
}

.button.in, .button.out {
    background-color: #8394a6;
}

.footer {
    display: flex;
    justify-content: center;
}



</style>